/**
 * 自定义函数
 * 调用：函数名
 * 
 */
import { http } from "@/config/utils/http";
import { notification } from "ant-design-vue";
import { useRoute } from "vue-router";
import { BASE_URL } from "@/../public/config";
/**
 * 通知弹出框封装
 * @param {*} type 
 * @param {*} msg 
 * @param {*} time 
 */
export function notice(type, msg, time = 1) {
    notification[type]({
        duration: time,
        message: msg,
    });
}
/**
 * 获取请求地址
 * @returns 
 */
export function baseUrl() {
    return BASE_URL;
}
/**
 * 获取基本网址
 * @returns 
 */
export function domainUrl() {
    var domain = BASE_URL.split("/");
    if (domain[0] && domain[2]) {
        return domain[0] + "//" + domain[2];
    }
    return '';
}
/**
 * 判断元素是否在数组中
 * @param {*} search 
 * @param {*} array 
 * @returns 
 */
export function in_array(search, array) {
    for (var i in array) {
        if (array[i] == search) {
            return true;
        }
    }
    return false;
}
/**
 * json编码解码,默认编码
 */
export function json(json, type = true) {
    if (type) {
        return JSON.stringify(json)
    }
    return eval('(' + json + ')')

}
/**
 * 清除登录信息 
 */
export function clearLogin() {
    cache('leftMenuRightOpenKeys', null)
    cache('adminMenuAuth', null)
    cache('adminMenuList', null)
    cache('DarkLeftMenu', null)
    cache('adminUserInfo', null)
}
/**
 * 权限验证
 * @param {*} type 
 */
export function auth(path) {
    const route = useRoute();
    const adminMenuAuth = cache('adminMenuAuth')
    const roles = adminMenuAuth['auth'];
    // 超管时
    if (adminMenuAuth.is_super) {
        return true
    }

    let item = {}
    for (const k in roles) {
        if (roles[k]['path'] == route.path) {
            item = roles[k]
            break
        }
    }
    // 没有任何权限时
    if (isEmptyObject(item)) {
        return false
    }
    // 为菜单验证时
    if (path == route.path) {
        return true
    }
    if (!item.action) {
        return false
    }
    if (isEmptyObject(item.action)) {
        return false
    }
    let fag = false
    for (const k in item['action']) {
        if (item['action'][k]['path'] == path) {
            fag = true
            break
        }
    }
    return fag

}
/**
 * 是否为空对象
 * @param {*} object 
 * @returns 
 */
export function isEmptyObject(object) {
    return Object.keys(object).length === 0
}
/**
 * 判断是否是对象
 * @param {*} array 
 * @returns 
 */
export function isArray(array) {
    return Object.prototype.toString.call(array) === '[object Array]'
}
/**
 * 请求二次封装，解决缓存不是最新的bug
 * @param {url,method,data,headers,tokenName} 
 * @returns 
 */
export function axios({ url, method = "post", data = {}, headers = {}, tokenName = 'Authorization-Token' }) {
    var adminUserInfo = cache('adminUserInfo')
    var HttpsToken = adminUserInfo && adminUserInfo[tokenName] ? adminUserInfo[tokenName] : false
    headers[tokenName] = headers[tokenName] ? headers[tokenName] : HttpsToken
    return http({
        url,
        headers,
        method,
        data
    })
}
/**
 * 刷新右边主体内容滚动高度
 * @param {*}
 * @returns 
 */
export function refreshScrollTop() {
    var bodyPage = document.getElementsByClassName('ant-layouts-content-body')[0]
    bodyPage ? bodyPage.scrollTop = 0 : false
}
/**
 * 深拷贝，解决指针问题
 * @param {*} obj 
 * @returns 
 */
export function deepCopy(obj) {
    return JSON.parse(JSON.stringify(obj));
}
/**
 * 获取最顶级父级路由
 * @param {data} 路由数组 
 * @param {path} 被查路由 
 */
export function getLeftTopRoute(data) {
    var findParent = (list, letMenuPath) => {
        for (let i = 0; i < list.length; i++) {
            list[i]['letMenuPath'] = letMenuPath
            if (list[i]['children']) {
                list[i]['children'] = findParent(list[i]['children'], letMenuPath)
            }
        }
        return list
    }

    for (let i = 0; i < data.length; i++) {
        data[i]['letMenuPath'] = data[i]['path']
        if (data[i]['children']) {
            data[i]['children'] = findParent(data[i]['children'], data[i]['path'])
        }
    }
    return data
}
/**
 * 匹配当前路由信息
 * @param {*} data 
 */
export function getRouteInfo(data, path) {
    // 多维数组变一维数组
    var newData = []
    var findChildren = (list) => {
        for (let i = 0; i < list.length; i++) {
            newData.push(list[i])
            if (list[i].children) {
                list[i]['children'] = findChildren(list[i].children)
            }
        }
    }
    for (let i = 0; i < data.length; i++) {
        newData.push(data[i])
        if (data[i].children) {
            findChildren(data[i].children)
        }
    }
    // 匹配当前路由信息
    let letMenuPath = ''
    for (let i = 0; i < newData.length; i++) {
        if (newData[i]['path'] == path) {
            letMenuPath = newData[i]['letMenuPath']
        }
    }
    return letMenuPath
}
/**
 * [cache 本地缓存]
 * 读取：cache(key)
 * 设置：cache(key,value)
 * 删除单个：cache(key,null)
 * 清除所有：cache(null)
 * @param  {[type]} key   [索引]
 * @param  {[type]} value [缓存值]
 * @param  {[type]} time  [有效期(秒)]
 */
export function cache(key, value, time) {
    if (typeof key != 'undefined' && key != null && typeof value != 'undefined' && value != null) {
        if (typeof time !== 'undefined' && time != null) {
            let expirse = Number(Math.round(new Date() / 1000)) + Number(time);
            let setdata = { value: value, expirse: expirse };
            window.localStorage.setItem(key, JSON.stringify(setdata));
        } else {
            let setdata = { value: value };
            window.localStorage.setItem(key, JSON.stringify(setdata));
        }
    } else if (typeof key !== 'undefined' && key !== null && typeof value === 'undefined') {
        window.localStorage.setItem('ie-edge', JSON.stringify(Number(Math.round(new Date() / 1000))));
        var getvalue = JSON.parse(window.localStorage.getItem(key));
        if (getvalue && getvalue != undefined && getvalue != null) {
            if (getvalue.expirse != undefined && getvalue.expirse != null && getvalue.expirse < Math.round(new Date() / 1000)) {
                window.localStorage.removeItem(key);
                return '';
            } else {
                return getvalue.value;
            }
        }
        return '';
    } else if (typeof key !== 'undefined' && key !== null && typeof value !== 'undefined' && value === null) {
        window.localStorage.removeItem(key);
        window.localStorage.removeItem('ie-edge');
    } else {
        window.localStorage.clear();
    }
}